<template>
  <!-- 表格 end  弹框-->
  <a-modal
    :title="isEditProject ? $t('all.autotext1141') : $t('all.autotext1385')"
    :visible="innerVisible"
    @cancel="clickCancel()"
    @ok="clickConfirm()"
    :confirmLoading="confirmLoading"
    width="650px"
    :okText="$t('all.autotext321')"
  >
    <a-form-model
      ref="ruleForm"
      :rules="rules"
      :model="form"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 15 }"
    >
      <a-form-model-item :label="$t('all.autotext992')" prop="no">
        <a-input
          v-model="form.no"
          :disabled="isClosed"
          :placeholder="$t('all.autotext445')"
          :max-length="50"
        />
      </a-form-model-item>
      <a-form-model-item :label="$t('all.autotext613')" prop="name">
        <a-textarea
          v-model="form.name"
          :maxLength="800"
          :disabled="isClosed"
          :placeholder="$t('all.autotext167')"
          :rows="2"
        />
      </a-form-model-item>
      <a-form-model-item :label="$t('all.autotext1718')" prop="businessCode">
        <a-select
          v-model="form.businessCode"
          show-search
          :filter-option="filterOption"
          :placeholder="$t('all.autotext1348')"
          allowClear
          :disabled="isClosed"
          @change="businessCodeChange"
        >
          <a-select-option v-for="list in businessList" :key="list.businessCode">
            {{ list.businessCode }}
          </a-select-option>
        </a-select>
      </a-form-model-item>
      <template v-if="form.businessCode">
        <a-form-model-item :label="$t('all.autotext1273')">
          {{ sponsorName }}
          <!--          <a style="margin-left: 15px;" @click="addBidders">{{ $t('all.autotext32') }}</a>-->
        </a-form-model-item>
        <a-form-model-item :label="$t('all.autotext1789')">
          <div v-if="customerName">{{ customerName }}</div>
          <div v-else style="color: red;">{{ $t('all.autotext1801') }}</div>
        </a-form-model-item>
      </template>
      <!-- ep v2.0: 默认项目状态未启动，无需展示 -->
      <a-form-model-item v-if="isEdit" :label="$t('all.autotext345')" prop="status">
        <a-radio-group v-model="form.status">
          <a-radio
            :value="1"
            :disabled="Boolean(isEdit) && beforeStatus > 1 && !isClosed"
          >
            {{ $t('all.autotext392') }}
          </a-radio>
          <a-radio
            :value="2"
            :disabled="Boolean(isEdit) && beforeStatus > 2 && !isClosed"
          >
            {{ $t('all.autotext1075') }}
          </a-radio>
          <a-radio :value="3">{{ $t('all.autotext1410') }}</a-radio>
        </a-radio-group>
      </a-form-model-item>
      <a-form-model-item
        :label="$t('all.autotext726')"
        prop="serviceRadios"
        class="form-radios"
        v-if="isAdmin"
      >
        <a-radio-group v-model="serviceChargeType" :disabled="isClosed" @change="handleServiceTypeChange" >
          <a-radio v-for="item in serviceChargeRadios" :key="item.value" :value="item.value">
            <div style="display: inline-flex;">
              <span :style="{color: serviceChargeType === item.value ? '#1890ff' : '', flexBasis: '150px', flexShrink: 0}">{{ item.label }}</span>
              <template v-if="[1, 2].includes(item.value) && serviceChargeType === item.value">
                <a-input
                  class="check"
                  v-model="form[item.prop]"
                  :placeholder="item.tips"
                  style="width:200px;"
                  :min="0.01"
                  :precision="2"
                  :maxLength="12"
                  @change="(e) => handleServiceChargeInput(e.target.value, item.prop)"
                />
                <span style="margin-left: 12px; font-size: 14px;">{{ item.unit }}</span>
              </template>
            </div>
          </a-radio>
        </a-radio-group>
      </a-form-model-item>
      <a-form-model-item v-if="form.businessCode" :label="$t('all.autotext1829')" prop="advancedPay">
        <a-radio-group  disabled v-model="form.advancedPay">
          <a-radio :value="1">{{ $t("all.autotext1830") }}</a-radio>
          <a-radio :value="0">{{ $t("all.autotext1831") }}</a-radio>
        </a-radio-group>
      </a-form-model-item>
      <a-form-model-item :label="$t('all.autotext873')" prop="protocolNo" :max-length="100">
        <a-input v-model="form.protocolNo" :disabled="isClosed" :placeholder="$t('all.autotext1067')" />
      </a-form-model-item>
      <a-form-model-item :label="$t('all.autotext863')" prop="stage">
        <a-select  :disabled="isClosed" v-model="form.stage" :placeholder="$t('all.autotext536')" >
          <a-select-option v-for="item in $const.SPONSOR_STAGE" :key="item.value" :value="item.value">
            {{ item.desc }}
          </a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item
        :label="$t('all.autotext480')"
        prop="createrId"
        v-if="isEditProject ? (this.$store.getters.userInfo.isAdmin ? true : false) : false"
      >
        <a-select
          v-model="form.createrId"
          :disabled="isClosed"
          :placeholder="$t('all.autotext1019')"
          allowClear
        >
          <a-select-option v-for="item in business" :key="item.key" :value="item.id">
            {{ item.name }}
          </a-select-option>
        </a-select>
      </a-form-model-item>
      <a-form-model-item :label="$t('all.autotext865')" prop="receiver">
        <a-select
          v-model="form.receiver"
          mode="multiple"
          :disabled="isClosed"
          show-search
          :filter-option="filterOption"
          :placeholder="$t('all.autotext812')"
        >
          <a-select-option v-for="list in noticeList" :key="list.id">
            {{ list.name }}
          </a-select-option>
        </a-select>
      </a-form-model-item>
    </a-form-model>
    <AddSponsorModal
      :visible="showModal"
      @modalOk="addSubmit"
      @modalCancel="addCancel"
      :type="1"
      :openType="0"
      :editContent="modify"
      :business="sponsorBusiness"
    />

    <identityCheck ref="identityRef" @ok="handleOk" @cancel="handleCancel" />
  </a-modal>
</template>
<script>
import AddSponsorModal from './components/AddSponsorModal.vue'
import { getDictionary, getInstitutionsAdd } from '@/api/organization/organization'
import { getAdminList, countAllFeeApply } from '@/api/common'
import clonedeep from 'lodash.clonedeep'
import { listAll } from '@api/system/user'
import { busNumberList } from '@/api/entry/entry'
import modalMixin from '@/utils/modal.mixin'
import identityCheck from '@views/cost-auditing/components/identityCheck'
import isNull from 'lodash/isNull'
import isUndefined from 'lodash/isUndefined'

export default {
  mixins: [modalMixin],
  components: { identityCheck, AddSponsorModal },
  props: {
    isEditProject: {
      default: false,
      type: Boolean
    },
    editContent: {
      type: Object,
      default: () => {}
    },
    isEdit: {
      type: Number,
      default: 0
    }
  },
  computed: {
    isAdmin () {
      return ['SYS_ADMIN', 'SYS_FINANCE', 'SYS_BIZ', 'PROJECT_ADMIN'].includes(this.$store.getters.role.code)
    },
    isClosed () {
      return this.editContent.status === 3
    },
    canEdit () {
      // && this.hasApply
      return Boolean(this.isEdit) && [1, 2].includes(this.editContent.status)
    }
  },
  data () {
    const validatorServiceRadios = (rule, val, cb) => {
      const { prop } = this.serviceChargeRadios.find(e => e.value === this.serviceChargeType)
      if (prop !== 'free' && !this.form[prop]) {
        cb(new Error(this.$t('all.autotext1081')))
      } else {
        cb()
      }
    }
    return {
      statusList: [
        {
          value: 1,
          desc: this.$t('all.autotext392')
        },
        {
          value: 2,
          desc: this.$t('all.autotext1075')
        },
        {
          value: 3,
          desc: this.$t('all.autotext1410')
        }
      ],
      beforeStatus: null,
      noticeList: [],
      identityCheckShow: false,
      form: {
        status: 1,
        serviceCharge: '',
        serviceChargePercent: '',
        advancedPay: 0 // 是否垫付
      },
      sponsorName: '',
      customerName: '',
      serviceChargeType: 1,
      serviceChargeRadios: [
        { prop: 'serviceCharge', label: this.$t('all.autotext1181.1'), value: 1, tips: this.$t('all.autotext1181.2'), unit: this.$t('all.autotext811') },
        { prop: 'serviceChargePercent', label: this.$t('all.autotext968.1'), value: 2, tips: this.$t('all.autotext968.2'), unit: '%' },
        { prop: 'free', label: this.$t('all.autotext208'), value: 0 }
      ],
      business: [],
      rules: {
        // 校验规则
        protocolNo: [
          { required: false, message: this.$t('all.autotext1332'), trigger: 'change' },
          { pattern: /^[0-9a-zA-Z-_]{1,}$/, message: this.$t('all.autotext387') }],
        name: [
          { required: true, message: this.$t('all.autotext552'), trigger: 'change' },
          { max: 500, message: this.$t('all.autotext1441') }
        ],
        businessCode: [{ required: true, message: this.$t('all.autotext1723'), trigger: 'change' }],
        status: [{ required: true, message: this.$t('all.autotext356'), trigger: 'change' }],
        no: [
          { required: true, message: this.$t('all.autotext1327'), trigger: 'change' },
          { pattern: /^[0-9a-zA-Z-_]{1,}$/, message: this.$t('all.autotext1400') }],
        createrId: [{ required: false, message: this.$t('all.autotext1417'), trigger: 'change' }],
        serviceRadios: [{ required: true, validator: validatorServiceRadios, trigger: 'change' }]
      },
      modify: {},
      showModal: false,
      sponsorBusiness: [],
      businessList: [],
      contractList: [],
      hasApply: false,
      confirmLoading: false
    }
  },
  methods: {
    modalUpdated () {
      this.beforeStatus = this.editContent.status
      this.form = this.isEdit === 0 ? { status: 1 } : clonedeep(this.editContent)
      this.form.advancedPay = this.advancedPay || 0
      this.sponsorName = this.form.sponsorName
      this.customerName = this.form.customerName
      const setServiceChargeType = () => {
        const { serviceCharge, serviceChargePercent } = this.editContent
        this.serviceChargeType = 1
        if (this.isEditProject) {
          this.serviceChargeType = (serviceCharge !== '' && !isNull(serviceCharge) && !isUndefined(serviceCharge))
            ? 1
            : (serviceChargePercent !== '' && !isNull(serviceChargePercent) && !isUndefined(serviceChargePercent))
              ? 2
              : 0
        }
      }
      setServiceChargeType()

      const businessIds = this.business.map(item => item.id)
      if (businessIds.indexOf(this.editContent.createrId) < 0) this.form.createrId = this.editContent.businessName
      // if (this.editContent.status === 3) {
      //   this.rules.advancedPay = []
      // } else {
      //   this.rules.advancedPay = [{ required: true, message: '请选择是否垫付', trigger: 'change' }]
      // }
      this.getBusinessCode()
      this.getCountAllFeeApply()
    },
    async getCountAllFeeApply () {
      if (!this.isEdit) return
      const res = await countAllFeeApply()
      this.hasApply = res
    },
    handleOk () {
      const businessIds = this.business.map(item => item.id)
      if (businessIds.indexOf(this.form.createrId) < 0) this.form.createrId = this.editContent.createrId
      const commitData = JSON.parse(JSON.stringify(this.form))
      commitData.receiver = commitData.receiver ? commitData.receiver?.toString() : ''
      commitData.statusDesc = this.statusList.find(item => Number(item.value) === commitData.status).desc
      let key = Object.keys(this.$const.SPONSOR_STAGE).find(item => this.$const.SPONSOR_STAGE[item].value === commitData.stage)
      commitData.stageDesc = this.$const.SPONSOR_STAGE[key]?.desc || ''
      commitData.sponsorIds = this.businessList.find(item => item.businessCode === this.form.businessCode).sponsorId
      commitData.customerId = this.businessList.find(item => item.businessCode === this.form.businessCode).customerId

      // 日志部分数据处理
      let beforeData = clonedeep(this.editContent)
      beforeData.statusDesc = beforeData.status ? this.statusList.find(item => Number(item.value) === beforeData.status).desc : ''
      let beforeKey = Object.keys(this.$const.SPONSOR_STAGE).find(item => this.$const.SPONSOR_STAGE[item].value === beforeData.stage)
      beforeData.stageDesc = beforeKey ? this.$const.SPONSOR_STAGE[beforeKey].desc : ''
      commitData.beforeData = JSON.stringify(beforeData)

      this.$emit('modalOk', commitData)
      setTimeout(() => {
        this.confirmLoading = false
      }, 5000)
    },
    handleCancel () {
      this.confirmLoading = false
    },
    modalInit () {
      this.getAdminList()
      this.getNoticeList()
      this.getBodyType()
    },
    // 查询合同号列表
    async getBusinessCode () {
      const res = await busNumberList({
        pageNumber: 1,
        pageSize: -1,
        status: 0 // 过滤掉已关闭的项目
      })
      this.businessList = res.content || []
    },
    businessCodeChange (e) {
      this.sponsorName = this.businessList.find(item => item.businessCode === e).sponsorName
      this.customerName = this.businessList.find(item => item.businessCode === e).customerName
      this.form.advancedPay = this.businessList.find(item => item.businessCode === e).advancedPay || 0 // 之前的项目可能没有选中，默认未垫付好了
    },
    async getNoticeList () {
      const res = await listAll()
      this.noticeList = res
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    // 获取机构列表传给新建申办方组件
    getBodyType () {
      getDictionary({
        typeCode: 10001011
      }).then(res => {
        this.sponsorBusiness = res
      })
    },
    addBidders () {
      this.modify = {}
      this.showModal = true
    },
    // 获取业务人员下拉列表
    getAdminList () {
      getAdminList()
        .then(res => {
          this.business = res
        })
    },
    clickConfirm () {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          if (!this.customerName) return
          this.confirmLoading = true
          this.$refs.identityRef.open()
        } else {
          return false
        }
      })
    },
    clickCancel () {
      this.innerVisible = false
      setTimeout(() => {
        this.$refs.ruleForm.resetFields()
        this.form = {
          status: 1,
          serviceCharge: '',
          serviceChargePercent: '',
          advancedPay: ''
        }
      }, 100)
    },
    // 新增申办方
    addSubmit (e) {
      getInstitutionsAdd({ ...e, type: 1 })
        .then(res => {
          this.showModal = false
          this.$message.success(this.$t('all.autotext1243'))
        })
    },
    // 取消新增申办方
    addCancel () {
      this.showModal = false
    },
    handleServiceTypeChange (e) {
      const val = e.target.value
      this.serviceChargeRadios.forEach(item => {
        if (val !== item.value && item.prop !== 'free') {
          this.form[item.prop] = ''
        }
      })
    },
    handleServiceChargeInput (val, prop) {
      const reg = /^-?[0-9]*(\.[0-9]*)?$/
      if ((!isNaN(val) && reg.test(val))) {
        this.form[prop] = this.$options.filters.amountCheck(val)
      } else {
        this.form[prop] = this.$options.filters.amountCheck(val.slice(0, -1))
      }
      this.$refs.ruleForm.clearValidate('serviceRadios')
    }
  }
}
</script>
<style lang="less" scoped>
.form-service {
  position: absolute;
  margin: -64px 0 0 180px;
  /deep/.ant-form-explain {
    margin-left: 20px;
  }
}
.form-radios {
  /deep/ .ant-radio-wrapper {
    display: block;
    height: 40px;
    line-height: 40px;
  }
}
</style>
